package com.quartzd.core.aspect;

import com.quartzd.consts.JobConst;
import com.quartzd.core.config.QuartzConfig;
import com.quartzd.core.enums.QuartzStatus;
import com.quartzd.entity.JobInfo;
import com.quartzd.service.QuartzInfoService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 描述：创建调度任务切面
 *
 * @author huxuehao
 **/
@Aspect
@Order(-1) /* 该切面应当先于 @Transactional 执行 */
@Component
public class QuartzCreateAspect extends QuartzAspect {
    public QuartzCreateAspect(QuartzInfoService quartzStatusService) {
        super(quartzStatusService);
    }

    @Pointcut("@annotation(com.quartzd.core.annotation.QuartzCreate)")
    public void quartzCreatePointcut() {

    }

    @AfterReturning(pointcut = "quartzCreatePointcut()", returning = "result")
    public void afterReturning(JoinPoint joinPoint, Object result) {
        if (result == null) return;
        QuartzConfig config = (QuartzConfig)result;
        JobInfo jobInfo = new JobInfo();
        jobInfo.setId(config.getIdentity());
        jobInfo.setCron(config.getCron());
        jobInfo.setJobClass(config.getJobClass().getName());
        Object dataMap = config.getDataMap().get(JobConst.DATA_MAP_KEY);
        jobInfo.setDataMap(dataMap == null ? "" : dataMap.toString());
        jobInfo.setStatus(QuartzStatus.START.value());
        jobInfo.setLastTime(new Date());
        saveStatus(jobInfo);
    }
}
